package com.lb.uts.web;

import com.lb.uts.annotation.Modify;
import com.lb.uts.constants.BaseResponse;
import com.lb.uts.constants.UTSConstants;
import com.lb.uts.entity.ActiveClient;
import com.lb.uts.entity.System;
import com.lb.uts.service.ISystemService;
import com.lb.uts.util.IdUtils;
import com.lb.uts.util.PolicyUtil;
import com.lb.uts.service.IActiveClientService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 执行器操作
 *
 * @Author liangb
 * @Date 2019/4/26 15:26
 */
@Controller
@RequestMapping("activeClient")
public class ActiveClientController extends UtsBaseController {

    private static final Logger logger = LoggerFactory.getLogger(ActiveClientController.class);

    @Autowired
    private ISystemService systemService;

    @Autowired
    private IActiveClientService activeClientService;

    /**
     * 查询全部执行器，分页查询
     *
     * @param model
     * @param systemName 系统名
     * @param pageNo     页数，默认1
     * @param pageSize   每页大小，默认10
     * @return 执行器list页面
     */
    @RequestMapping("list")
    public String list(Model model, @ModelAttribute("systemName") String systemName, @RequestParam(value = "pageNum", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        model.addAttribute("page", activeClientService.queryBySystemName(systemName, pageNo, pageSize));
        model.addAttribute("systemList", systemService.queryByEntity(new System()));
        return "active/list";
    }


    /**
     * 新增执行器</p>
     * 简单的参数验证：</p>
     *
     * @param activeClient 执行器信息
     * @return 返回增加结果
     * @see Validated
     * @see ActiveClient
     */
    @RequestMapping("add")
    @ResponseBody
    @Validated
    @Modify
    public BaseResponse add(ActiveClient activeClient) {
        logger.info("插入active:" + activeClient.toString());
        activeClient.setId(IdUtils.nextUUID());
        activeClient.setCreateTime(LocalDateTime.now());
        int num = activeClientService.insert(activeClient);
        List<Map<String, String>> ipsStringMap = activeClientService.groupBySystemName();
        PolicyUtil.updateJobIpList(ipsStringMap);
        return num == 1 ? wrapSuccessResp(BaseResponse.class) : wrapErrResp(BaseResponse.class, "插入失败");
    }


    /**
     * 删除执行器
     *
     * @param id 主键id
     * @return
     */
    @RequestMapping("delete/{id}")
    @ResponseBody
    @Modify
    public BaseResponse delete(@PathVariable("id") String id) {
        logger.info("删除active:" + id);
        int num = activeClientService.deleteById(id);
        return num == 1 ? wrapSuccessResp(BaseResponse.class) : wrapErrResp(BaseResponse.class, "删除失败");
    }


    /**
     * 更新执行器
     *
     * @param activeClient 执行器信息
     * @return 修改结果
     * @see Validated
     * @see ActiveClient
     */
    @RequestMapping("update")
    @ResponseBody
    @Validated
    @Modify
    public BaseResponse update(ActiveClient activeClient) {
        logger.info("更新active:" + activeClient.toString());
        String id = activeClient.getId();
        if (StringUtils.isBlank(id)) {
            return wrapErrResp(BaseResponse.class, "id不能为空");
        }
        ActiveClient inDb = activeClientService.getById(id);
        if (inDb == null) {
            return wrapErrResp(BaseResponse.class, "记录不存在");
        }
        inDb.setIp(activeClient.getIp());
        inDb.setSystemName(activeClient.getSystemName());
        int num = activeClientService.update(inDb);
        List<Map<String, String>> ipsStringMap = activeClientService.groupBySystemName();
        PolicyUtil.updateJobIpList(ipsStringMap);
        return num == 1 ? wrapSuccessResp(BaseResponse.class) : wrapErrResp(BaseResponse.class, "更新失败");
    }


    /**
     * 编辑执行器，返回json数据
     *
     * @param id 主键
     * @return
     */
    @RequestMapping("edit/{id}")
    @ResponseBody
    public Map<String, Object> editSystem(@PathVariable("id") String id) {
        Map<String, Object> result = new HashMap<>();
        ActiveClient activeClient = activeClientService.getById(id);
        if (activeClient == null) {
            result.put("returnCode", UTSConstants.FAIL_CODE);
            result.put("returnMsg", "记录不存在");
        } else {
            result.put("returnCode", UTSConstants.SUCCESS_CODE);
            result.put("active", activeClient);
        }
        return result;
    }
}
